<template>
  <div class="w-full bg-white rounded-2xl ring-1 ring-gray-200 p-3 flex items-end gap-2">
    <textarea 
      ref="textareaRef"
      v-model="message"
      @keydown="handleKeydown"
      @input="adjustHeight"
      :class="['flex-1','resize-none','outline-none','text-sm','placeholder:text-gray-400', allowScroll ? 'overflow-y-auto' : 'overflow-y-hidden']"
      :style="{ height: currentHeightPx + 'px', maxHeight: doubleHeightPx + 'px' }"
      placeholder="输入你的消息..." 
      :disabled="isLoading"
    />
    <div class="flex items-center gap-2">
      <!-- <button 
        class="h-10 w-10 rounded-xl ring-1 ring-gray-200 text-gray-500 hover:bg-gray-50" 
        title="上传"
        :disabled="isLoading"
      >
        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mx-auto" viewBox="0 0 24 24" fill="currentColor"><path d="M5 20h14v-2H5v2zm7-18l-5 5h3v4h4V7h3l-5-5z"/></svg>
      </button> -->
      <button 
        class="h-10 w-10 rounded-xl ring-1 ring-gray-200 text-gray-500 hover:bg-gray-50" 
        title="语音"
        :disabled="isLoading"
        @click="emit('openVoice')"
      >
        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mx-auto" viewBox="0 0 24 24" fill="currentColor"><path d="M12 14a3 3 0 003-3V5a3 3 0 10-6 0v6a3 3 0 003 3zm5-3a5 5 0 11-10 0H5a7 7 0 0014 0h-2zM11 19h2v3h-2v-3z"/></svg>
      </button>
      <button 
        @click="sendMessage"
        :disabled="!message.trim() || isLoading"
        class="h-10 px-4 rounded-xl bg-[#635BFF] text-white text-sm disabled:opacity-50 disabled:cursor-not-allowed"
      >
        <span v-if="!isLoading">发送</span>
        <span v-else class="flex items-center gap-1">
          <svg class="animate-spin h-4 w-4" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" fill="none"/>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"/>
          </svg>
          发送中
        </span>
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted, onUnmounted, watch } from 'vue'

interface Props {
  isLoading?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  isLoading: false
})

const emit = defineEmits<{
  send: [message: string]
  openVoice: []
}>()

const message = ref('')
const textareaRef = ref<HTMLTextAreaElement>()

// 本地存储相关
const STORAGE_KEY = 'chat-composer-message'
let saveTimeout: ReturnType<typeof setTimeout> | null = null

// 从本地存储加载消息
const loadMessageFromStorage = () => {
  try {
    const stored = localStorage.getItem(STORAGE_KEY)
    if (stored) {
      message.value = stored
      console.log('已从本地存储恢复输入内容:', message.value)
    }
  } catch (error) {
    console.error('加载本地存储数据失败:', error)
  }
}

// 保存消息到本地存储
const saveMessageToStorage = () => {
  try {
    localStorage.setItem(STORAGE_KEY, message.value)
    console.log('已保存输入内容到本地存储:', message.value)
  } catch (error) {
    console.error('保存到本地存储失败:', error)
  }
}

// 清空本地存储
const clearMessageStorage = () => {
  try {
    localStorage.removeItem(STORAGE_KEY)
    console.log('已清空本地存储')
  } catch (error) {
    console.error('清空本地存储失败:', error)
  }
}

// 高度控制：基础高度 48px（h-12），双倍高度 96px
const baseHeightPx = 48
const doubleHeightPx = 96
const currentHeightPx = ref(baseHeightPx)
const isExpanded = ref(false)
const allowScroll = ref(false)

// 监听消息变化，自动保存到本地存储
watch(message, () => {
  // 使用防抖，避免频繁保存
  if (saveTimeout) {
    clearTimeout(saveTimeout)
  }
  saveTimeout = setTimeout(() => {
    saveMessageToStorage()
  }, 500)
})

// 页面加载时恢复数据
onMounted(() => {
  loadMessageFromStorage()
})

// 页面卸载时清理定时器
onUnmounted(() => {
  if (saveTimeout) {
    clearTimeout(saveTimeout)
  }
})

// 发送消息
const sendMessage = () => {
  console.log('Composer sendMessage 被调用')
  console.log('message.value:', message.value)
  console.log('props.isLoading:', props.isLoading)
  
  if (!message.value.trim() || props.isLoading) {
    console.log('消息为空或正在加载，跳过发送')
    return
  }
  
  console.log('触发send事件:', message.value.trim())
  emit('send', message.value.trim())
  
  // 发送成功后清空输入框和本地存储
  message.value = ''
  clearMessageStorage()
  
  // 重置高度状态
  isExpanded.value = false
  allowScroll.value = false
  currentHeightPx.value = baseHeightPx
}

// 处理键盘事件
const handleKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    sendMessage()
  }
}

// 自动调整高度：
// - 未展开时，当内容高度超过基础高度，仅提升到双倍高度一次
// - 展开后保持双倍高度，超过则内部滚动
const adjustHeight = () => {
  nextTick(() => {
    const el = textareaRef.value
    if (!el) return
    // 先恢复为基础或双倍高度，获取正确的 scrollHeight
    el.style.height = (isExpanded.value ? doubleHeightPx : baseHeightPx) + 'px'
    const needed = el.scrollHeight

    if (!isExpanded.value) {
      if (needed > baseHeightPx) {
        // 首次超过，拉高到双倍
        isExpanded.value = true
        currentHeightPx.value = doubleHeightPx
      } else {
        currentHeightPx.value = baseHeightPx
      }
    } else {
      // 已经展开，保持双倍高度
      currentHeightPx.value = doubleHeightPx
    }

    // 只在内容超过双倍高度时允许滚动
    allowScroll.value = needed > doubleHeightPx
  })
}
</script>


